<template>
  <div class="avatar-container" :style="{ width: size + 'px', height: size + 'px' }">
    <img
      :src="displayAvatar"
      :alt="alt"
      class="avatar-image"
      @error="handleImageError"
      @load="handleImageLoad"
    />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

// 默认头像的base64编码
const defaultAvatarUrl = ''

// Props
const props = defineProps({
  src: {
    type: String,
    default: ''
  },
  size: {
    type: Number,
    default: 40
  },
  alt: {
    type: String,
    default: '用户头像'
  }
})

// 状态
const imageError = ref(false)

// 计算属性：显示的头像
const displayAvatar = computed(() => {
  if (imageError.value || !props.src) {
    return defaultAvatarUrl
  }
  return props.src
})

// 图片加载错误处理
const handleImageError = () => {
  imageError.value = true
}

// 图片加载成功处理
const handleImageLoad = () => {
  imageError.value = false
}
</script>

<style scoped>
.avatar-container {
  display: inline-block;
  border-radius: 50%;
  overflow: hidden;
  background-color: #f5f5f5;
  border: 2px solid #e5e7eb;
  transition: all 0.3s ease;
}

.avatar-container:hover {
  border-color: #667eea;
  transform: scale(1.05);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}
</style>
